//
//  ViewController+AOP.m
//  test
//
//  Created by hjk on 16/6/20.
//  Copyright © 2016年 何锦坤. All rights reserved.
//

#import "ViewController+AOP.h"
#import <objc/runtime.h>
#import <objc/message.h>

@implementation UIViewController (AOP)
+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class selfclass = [self class];
        //Class selfclass = object_getClass([self class]);
        
        //获取方法
        SEL orsel = @selector(viewDidAppear:);
        Method ormethod = class_getInstanceMethod(selfclass, orsel);
        
        SEL cussel = @selector(customViewWillAppear:);
        Method cusmethod = class_getInstanceMethod(selfclass, cussel);
        
        BOOL addsucc = class_addMethod(selfclass, orsel, method_getImplementation(cusmethod), method_getTypeEncoding(cusmethod));
        if (addsucc) {
            class_replaceMethod(selfclass, cussel, method_getImplementation(cusmethod), method_getTypeEncoding(cusmethod));
            
        }else{
            method_exchangeImplementations(ormethod, cusmethod);
        }
    });
    //objc_setAssociatedObject(self, @selector(customTabbar), customTabbar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(void)customViewWillAppear:(BOOL)animated
{
     NSLog(@"hello");
    [self customViewWillAppear:YES];
   
}

void TestMetaClass(id self, SEL _cmd) {
    NSLog(@"This objcet is %p", self);
    
    NSLog(@"Class is %@, super class is %@", [self class], [self superclass]);
    
    
    
    Class currentClass = [self class];
    
    for (int i = 0; i < 4; i++) {
        
        NSLog(@"Following the isa pointer %d times gives %p", i, currentClass);
        
        currentClass = objc_getClass((__bridge void *)currentClass);
        
    }
    
    
    
    NSLog(@"NSObject's class is %p", [NSObject class]);
    
    NSLog(@"NSObject's meta class is %p", objc_getClass((__bridge void *)[NSObject class]));
    unsigned int outCount = 0;
    Ivar *ivars = class_copyIvarList([self class], &outCount);
    //Class
}



#pragma mark -



- (void)ex_registerClassPair {
    
    
    
    Class newClass = objc_allocateClassPair([NSError class], "TestClass", 0);
    
    class_addMethod(newClass, @selector(testMetaClass), (IMP)TestMetaClass, "v@:");
    
    objc_registerClassPair(newClass);
    
    
    
    id instance = [[newClass alloc] initWithDomain:@"some domain" code:0 userInfo:nil];
    
    [instance performSelector:@selector(testMetaClass)];
    
}

@end
